package Action;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.dom4j.DocumentException;

import Beans.Admin;
import Beans.Agent;
import Beans.Company;
import Beans.Config;
import Beans.Courier;
import Beans.Express;
import Beans.LogPay;
import Beans.LogPayPackage;
import Beans.RechargeConfig;
import DAO.AgentDao;
import DAO.CompanyDao;
import DAO.ConfigDao;
import DAO.CourierDao;
import DAO.ExpenseDao;
import DAO.ExpressDao;
import DAO.LogPayDao;
import DAO.LogPayPackageDao;
import DAO.RechargeConfigDao;
import Utils.AlipayHelper;
import Utils.CheckPhoneHelper;
import Utils.MD5Helper;
import Utils.SendSMSHelper;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class ExpressAction extends ActionSupport {
	List<Express> expressBranchs;
	List<Company> companies;
	List<LogPay> logPays;
	List<Config> configs;
	List<LogPayPackage> logPayPackages;
	List<Courier> couriers;
	List<RechargeConfig> rechargeConfigs;

	ExpressDao expressBranchDao = new ExpressDao();
	CompanyDao companyDao = new CompanyDao();
	CourierDao courierDao = new CourierDao();
	AgentDao agentDao = new AgentDao();
	ExpenseDao expenseDao = new ExpenseDao();
	LogPayDao logPayDao = new LogPayDao();
	ConfigDao configDao = new ConfigDao();
	LogPayPackageDao logPayPackageDao = new LogPayPackageDao();
	RechargeConfigDao rechargeConfigDao = new RechargeConfigDao();

	private int expressBranchID;
	private int company = 0;
	private int expressId;
	private int agentID;
	private int status;
	private int payType;// 充值类型
	private int payConfID;// 充值配置id
	private BigDecimal money;
	private String serialNum;
	private String expressProvince;
	private String expressCity;
	private String accountPwd;
	private String messageResult;
	private BigInteger mobileNum;
	private Express express = new Express();
	private RechargeConfig rechargeConfig = new RechargeConfig();
	private LogPay logPay = null;
	private Config config = null;
	private Agent agent = null;

	Map<String, Object> message = new HashMap<String, Object>();

	/**
	 * 编辑快递网点
	 * 
	 * @return
	 */
	public String editExpress() {
		Express e = expressBranchDao.getExpressBranch(expressBranchID);
		if (agentID == 0) {
			agentID = 1;
		}
		if (mobileNum != null
				&& CheckPhoneHelper.isMobileNO(mobileNum.toString())) {
			express.setCourier(courierDao.getByMobileNum(mobileNum));
		}
		express.setCompany(companyDao.getCompanyById(company));
		express.setExpressProvince(expressProvince);
		express.setExpressCity(expressCity);
		express.setExpressId(expressBranchID);
		express.setAgent(agentDao.getAgentById(agentID));
		express.setExpressBalance(e.getExpressBalance());
		if (express.getPayway() == 0) {
			if (e.getExpressBalance().compareTo(express.getOverdue()) >= 0) {
				express.setStatus(0);
			} else {
				express.setStatus(1);
			}
		} else {
			express.setStatus(0);
		}
		expressBranchDao.edit(express);
		return "success";
	}

	/**
	 * 删除快递网点
	 * 
	 * @return
	 */
	public String deleteExpress() {
		if (courierDao.searchCourier(expressBranchID).size() > 0
				|| expenseDao.getAllExpense(
						expressBranchDao.getExpressBranch(expressBranchID))
						.size() > 0) {
		} else {
			express.setExpressId(expressBranchID);
			expressBranchDao.delete(express);
		}
		return "success";
	}

	/**
	 * 新增快递网点
	 * 
	 * @return
	 */
	public String registerExpress() {
		if (agentID == 0) {
			agentID = 1;
		}
		if (CheckPhoneHelper.isMobileNO(mobileNum.toString())) {
			express.setCourier(courierDao.getByMobileNum(mobileNum));
		}
		express.setCompany(companyDao.getCompanyById(company));
		express.setExpressProvince(expressProvince);
		express.setExpressCity(expressCity);
		express.setAgent(agentDao.getAgentById(agentID));
		express.setExpressBalance(new BigDecimal(0));
		express.setStatus(0);
		expressBranchDao.save(express);
		return "success";
	}
	/**
	 * 新增充值配置
	 * @return
	 */
	public String registerConf(){
		rechargeConfig.setExpress(expressBranchDao.getExpressBranch(expressId));
		rechargeConfigDao.save(rechargeConfig);
		return getPayConfig();
	}

	/**
	 * 获取所有快递网点
	 */
	public String getAllExpressCompany() {
		companies = companyDao.getAllcompany();
		couriers = courierDao.getAll();
		return "success";
	}

	/**
	 * 充值界面
	 * 
	 * @return
	 */
	public String payExpressPage() {
		express = expressBranchDao.getExpressBranchById(expressBranchID);
		return "payExpressPage";
	}

	/**
	 * 获取该快递网点充值详情
	 * 
	 * @return
	 */
	public String getExpressPayDetail() {
		logPays = logPayDao.getByExpBranchID(expressBranchID);
		return "payment";
	}

	/**
	 * 获取快递网点扣费详情
	 * 
	 * @return
	 */
	public String getExpressPayPackageDetail() {
		logPayPackages = logPayPackageDao.getByExpBranchID(expressBranchID);
		return "logPayPackage";
	}

	/**
	 * 获取快递网点详情
	 * 
	 * @return
	 */
	public String getExpressDetail() {
		express = expressBranchDao.getExpressBranchById(expressId);
		return "details";
	}

	/**
	 * 通过ID获取网点
	 */
	public String getExpressBranchList() {
		express = expressBranchDao.getExpressBranch(expressId);
		return "success";
	}

	public String getByExpressId() {
		express = expressBranchDao.getExpressBranch(expressId);
		expressBranchs = new ArrayList<Express>();
		expressBranchs.add(express);
		return "getExpress";
	}

	/**
	 * 检测财务密码
	 * 
	 * @return
	 */
	public String checkAccountPwd() {
		String pwd = configDao.getConfigById(2).getValue().toLowerCase();
		// accountPwd=MD5Helper.getMD5Str(accountPwd);
		if (pwd.equals(MD5Helper.getMD5Str(accountPwd))) {
			message.put("result", "success");
		} else {
			message.put("result", "failed");
		}
		return "jsonResult";
	}

	/**
	 * 通过ID获取网点
	 */
	public String getExpressById() {
		getAllExpressCompany();
		express = expressBranchDao.getExpressBranch(expressId);
		return "success";
	}
	/**
	 * 获取充值配置并修改
	 * @return
	 */
	public String getPayConfById() {
		rechargeConfig = rechargeConfigDao.getConfById(payConfID);
		return "payConfEdit";
	}
	/**
	 * 获取充值配置列表
	 * @return
	 */
	public String getPayConfig() {
		express = expressBranchDao.getExpressBranch(expressId);
		rechargeConfigs = rechargeConfigDao.getAll(express);
		return "payConfig";
	}
	/**
	 * 获取充值配置
	 * @return
	 */
	public String getPayConfigs(){
		express = expressBranchDao.getExpressBranch(expressId);
		rechargeConfigs = rechargeConfigDao.getAll(express);
		return "selectMoney";
	}

	/**
	 * 启用/停用网点
	 * 
	 * @return
	 */
	public String changeStatus() {
		expressBranchDao.changeStatus(expressBranchID, status);
		return getAllExpress();
	}

	/**
	 * 获取所有网点和公司
	 */
	public String getCompanyAndBranch() {
		companies = companyDao.getAllcompany();
		if (company != 0) {
			expressBranchs = expressBranchDao.getCompanyExpressBranch(company);
			return "jsonSuccess";
		} else {
			return "success";
		}

	}
	/**
	 * 删除配置
	 * @return
	 */
	public String deletePayConf(){
		rechargeConfig = rechargeConfigDao.getConfById(payConfID);
		rechargeConfigDao.delete(rechargeConfig);
		return getPayConfig();
	}
	/**
	 * 更新充值配置
	 * @return
	 */
	public String updatePayConf(){
		rechargeConfig.setExpress(expressBranchDao.getExpressBranch(expressId));
		rechargeConfigDao.edit(rechargeConfig);
		return getPayConfig();
	}

	/**
	 * 充值缴费
	 * @throws Exception 
	 * @throws DocumentException 
	 */
	public String payIn() throws DocumentException, Exception {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		Admin admin = (Admin) session.get("admin");
		express = expressBranchDao.getExpressBranch(expressId);
		agent = express.getAgent();
		rechargeConfigs = rechargeConfigDao.getAll(express,money);
		if(agent.getRecharge()==0){
			serialNum = AlipayHelper.getSerialNum("YB");
		}else{
			serialNum = AlipayHelper.getSerialNum(agent.getName());
		}
		BigDecimal zero = new BigDecimal(0);
		BigDecimal one = new BigDecimal(1);
		BigDecimal give = null;
		Timestamp timestamp = new Timestamp(new Date().getTime());
		if (payType == 1) {
			logPay = new LogPay(timestamp, admin,
					express, money,zero, payType, serialNum, "", "success");
			logPayDao.save(logPay);
			BigDecimal temp = express.getExpressBalance().add(money);
			if (express.getPayway() == 0 && temp.compareTo(zero) >= 0) {
				express.setStatus(0);
			}
			express.setExpressBalance(temp);
			expressBranchDao.edit(express);
			agent.setBalance(agent.getBalance().add(money));
			agentDao.edit(agent);
			return "success";
		} else if (payType == 0) {
			give = money.multiply(rechargeConfigs.get(0).getProportion().subtract(one));
			logPay = new LogPay(new Timestamp(new Date().getTime()), admin,
					express, money,give, payType, serialNum, "", "wait");
			logPayDao.save(logPay);
			HttpServletResponse response = ServletActionContext.getResponse();
			String url = AlipayHelper.buildURL(agent,serialNum, express.getCourier()
					.getMobileNum(), express.getExpressName(), money);
			response.sendRedirect(url);
			// response.sendRedirect("alipayapi.jsp?serialNum=" + serialNum
			// + "&money=" + money + "&phoneNum=" +
			// express.getCourier().getMobileNum());
			return null;
		} else {
			return null;
		}
	}

	/**
	 * 处理支付宝返回结果
	 * 
	 * @throws Exception
	 */
	public String returnPay() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		// 获取支付宝GET过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}

		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		// 商户订单号

		String out_trade_no = new String(request.getParameter("out_trade_no")
				.getBytes("ISO-8859-1"), "UTF-8");

		// 支付宝交易号

		String trade_no = new String(request.getParameter("trade_no").getBytes(
				"ISO-8859-1"), "UTF-8");

		// 交易状态
		String trade_status = new String(request.getParameter("trade_status")
				.getBytes("ISO-8859-1"), "UTF-8");

		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

		// 计算得出通知验证结果
		boolean verify_result = AlipayHelper.verify(params);

		// logPays = logPayDao.getBySerialNum(out_trade_no);
		// if(logPays.size()==1){
		// logPay = logPays.get(0);
		// express = logPay.getExpress();
		// express.setExpressBalance(logPay.getMoney() +
		// express.getExpressBalance());
		// expressBranchDao.payIn(express);
		// logPay.setStatus("success");
		// logPayDao.edit(logPay);
		// }

		// if (verify_result) {// 验证成功
		// ////////////////////////////////////////////////////////////////////////////////////////
		// 请在这里加上商户的业务逻辑程序代码
		logPays = logPayDao.getBySerialNum(out_trade_no);
		if (logPays.size() == 1) {
			logPay = logPays.get(0);
			express = logPay.getExpress();
			express.setExpressBalance(express.getExpressBalance().add(logPay.getMoney()).add(logPay.getGive()));
			expressBranchDao.payIn(express);
			agent = express.getAgent();//代理商余额充值
			agent.setBalance(agent.getBalance().add(logPay.getMoney()).add(logPay.getGive()));
			agentDao.edit(agent);
			logPay.setStatus("success");
			logPayDao.edit(logPay);
			messageResult = "充值成功！已为" + express.getExpressName() + "充值"
					+ logPay.getMoney() + "元，当前网点余额为"
					+ express.getExpressBalance() + "元。";
			SendSMSHelper.send(
					"充值成功！已为" + express.getExpressName() + "充值"
							+ logPay.getMoney() + "元，当前网点余额为"
							+ express.getExpressBalance() + "元。",
					String.valueOf(express.getCourier().getMobileNum()));
		}
		// ——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
		if (trade_status.equals("TRADE_FINISHED")
				|| trade_status.equals("TRADE_SUCCESS")) {
			messageResult = messageResult + "（已处理完毕）";
			// 判断该笔订单是否在商户网站中已经做过处理
			// 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
			// 如果有做过处理，不执行商户的业务程序
			// System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
		}

		// 该页面可做页面美工编辑
		// ——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

		// ////////////////////////////////////////////////////////////////////////////////////////
		// } else {
		// messageResult="验证失败！";
		// // 该页面可做页面美工编辑
		// }
		return "success";
	}

	/**
	 * 获取所有快递网点
	 */
	public String getAllExpress() {
		expressBranchs = expressBranchDao.getAllExpress();
		return "success";
	}

	public List<Express> getExpressBranchs() {
		return expressBranchs;
	}

	public void setExpressBranchs(List<Express> expressBranchs) {
		this.expressBranchs = expressBranchs;
	}

	public List<Company> getCompanies() {
		return companies;
	}

	public void setCompanies(List<Company> companies) {
		this.companies = companies;
	}

	public int getExpressBranchID() {
		return expressBranchID;
	}

	public void setExpressBranchID(int expressBranchID) {
		this.expressBranchID = expressBranchID;
	}

	public BigDecimal getMoney() {
		return money;
	}

	public void setMoney(BigDecimal money) {
		this.money = money;
	}

	public Express getExpress() {
		return express;
	}

	public void setExpress(Express express) {
		this.express = express;
	}

	public int getCompany() {
		return company;
	}

	public void setCompany(int company) {
		this.company = company;
	}

	public int getExpressId() {
		return expressId;
	}

	public void setExpressId(int expressId) {
		this.expressId = expressId;
	}

	public String getExpressProvince() {
		return expressProvince;
	}

	public void setExpressProvince(String expressProvince) {
		this.expressProvince = expressProvince;
	}

	public String getExpressCity() {
		return expressCity;
	}

	public void setExpressCity(String expressCity) {
		this.expressCity = expressCity;
	}

	public int getAgentID() {
		return agentID;
	}

	public void setAgentID(int agentID) {
		this.agentID = agentID;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public LogPay getLogPay() {
		return logPay;
	}

	public void setLogPay(LogPay logPay) {
		this.logPay = logPay;
	}

	public List<LogPay> getLogPays() {
		return logPays;
	}

	public void setLogPays(List<LogPay> logPays) {
		this.logPays = logPays;
	}

	public BigInteger getMobileNum() {
		return mobileNum;
	}

	public void setMobileNum(BigInteger mobileNum) {
		this.mobileNum = mobileNum;
	}

	public String getSerialNum() {
		return serialNum;
	}

	public void setSerialNum(String serialNum) {
		this.serialNum = serialNum;
	}

	public int getPayType() {
		return payType;
	}

	public void setPayType(int payType) {
		this.payType = payType;
	}

	public Map<String, Object> getMessage() {
		return message;
	}

	public void setMessage(Map<String, Object> message) {
		this.message = message;
	}

	public String getAccountPwd() {
		return accountPwd;
	}

	public void setAccountPwd(String accountPwd) {
		this.accountPwd = accountPwd;
	}

	public List<Config> getConfigs() {
		return configs;
	}

	public void setConfigs(List<Config> configs) {
		this.configs = configs;
	}

	public Config getConfig() {
		return config;
	}

	public void setConfig(Config config) {
		this.config = config;
	}

	public List<LogPayPackage> getLogPayPackages() {
		return logPayPackages;
	}

	public void setLogPayPackages(List<LogPayPackage> logPayPackages) {
		this.logPayPackages = logPayPackages;
	}

	public List<Courier> getCouriers() {
		return couriers;
	}

	public void setCouriers(List<Courier> couriers) {
		this.couriers = couriers;
	}

	public String getMessageResult() {
		return messageResult;
	}

	public void setMessageResult(String messageResult) {
		this.messageResult = messageResult;
	}

	public List<RechargeConfig> getRechargeConfigs() {
		return rechargeConfigs;
	}

	public void setRechargeConfigs(List<RechargeConfig> rechargeConfigs) {
		this.rechargeConfigs = rechargeConfigs;
	}

	public int getPayConfID() {
		return payConfID;
	}

	public void setPayConfID(int payConfID) {
		this.payConfID = payConfID;
	}

	public RechargeConfig getRechargeConfig() {
		return rechargeConfig;
	}

	public void setRechargeConfig(RechargeConfig rechargeConfig) {
		this.rechargeConfig = rechargeConfig;
	}

}
